package com.ls.common.util;

import com.alibaba.fastjson2.JSONObject;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;

import java.nio.charset.StandardCharsets;

/**
 * @Description  spring gateway 返回json数据给前端，在网关使用如下
 * DataBuffer buffer = responeUtils.getResponeBuffer(response);
 * return response.writeWith(Mono.just(buffer));
 * @Author konglz
 * @Data 2023/4/27 20:10
 */
public class ResponeUtils {

    public static DataBuffer getResponeBuffer(ServerHttpResponse response) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", HttpStatus.UNAUTHORIZED);
        jsonObject.put("message", "未认证");
        //把json对象转换成字节数组
        byte[] bits = jsonObject.toJSONString().getBytes(StandardCharsets.UTF_8);
        //把字节数据转换成一个DataBuffer
        DataBuffer buffer = response.bufferFactory().wrap(bits);
        return buffer;
    }
}

